//
//  Pet_TabbarViewController.swift
//  PetApp
//
//  Created by mac on 2023/9/18.
//  Copyright © 2023 Pet_. All rights reserved.
//

import UIKit
import HyphenateChat
import AgoraRtmKit
import AVFoundation

class Pet_TabbarViewController: UITabBarController,PixelWorldChatProtocol {
    
    let imageNames: [String] = ["icon1","icon2", "icon3", "icon4"]
    let scenes: [UIViewController] = [Pet_CardViewController(),Fish_WorryListViewController(),TEA_MessageViewController(), Pet_MineViewController()]
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }
        
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.tabBar.isTranslucent = true
        for i in 0..<scenes.count {
            configuration(viewController: scenes[i], imageName: imageNames[i])
        }
        
        setValue(MyTabBar(), forKey: "tabBar")
        IAPManager.shared.addTransactionObserver()
        AgoraRTMClient.shared.login()
        //登录成功
        AgoraRTMClient.shared._kit?.agoraRtmDelegate = self
        AgoraRTMClient.shared._kit?.getRtmCall()?.callDelegate = self
        chat.configChat(easyMobileKey)
        HyMessageClient.addDelegate(aDelegate: self)
        HyMessageClient.login(USEINFOMODEL.id?.intValue ?? 0, USEINFOMODEL.id?.intValue ?? 0) { userInfo, error in
            print("HyMessageClient====-====    ")
            print(userInfo)
            print(error?.code)
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(refrshDelegate), name: NSNotification.Name(rawValue: "changeDelegate"), object: nil)
        NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "refreshBadge"), object: nil, queue: .main) { _ in
            self.refreshUnreadCount()
        }
        
        weak var weakSelf = self
        self.chat.newMessages { result in
        }.unreadCount { result in
            guard let strongSelf = weakSelf else { return }
            /// 刷新未读消息数量
            strongSelf.refreshUnreadCount()
        }
        refreshUnreadCount()
        RT.getUserInfoUrlInfoWith { info in
        
        }

    }
        
    @objc func refreshUnreadCount() {
        let unreadCount = self.chat.allUnreadCount()
        if unreadCount != 0{
            scenes[2].tabBarItem.badgeValue = "\(unreadCount)"
        }else{
            scenes[2].tabBarItem.badgeValue = nil
        }
    }
    @objc func refrshDelegate(){
        AgoraRTMClient.shared._kit?.agoraRtmDelegate = self
        AgoraRTMClient.shared._kit?.getRtmCall()?.callDelegate = self
    }
    func configuration(viewController: UIViewController, imageName: String) {
        viewController.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal)
        viewController.tabBarItem.selectedImage = UIImage(named: imageName + " 1")?.withRenderingMode(.alwaysOriginal)
        let vc = NavigationInterface(rootViewController: viewController)
        addChild(vc)
    }
}


extension Pet_TabbarViewController: EMClientDelegate {}
extension Pet_TabbarViewController: EMChatManagerDelegate {
    /// 收到透传消息
    /// - Parameter aCmdMessages: 透传消息
    func cmdMessagesDidReceive(_ aCmdMessages: [Any]!) {
        debugPrint("[EASYMOB] - RECEIVED [CMD] MESSAGE - ", aCmdMessages ?? [])
    }
    
    /// 收到消息
    /// - Parameter aMessages: 收到的消息
    func messagesDidReceive(_ aMessages: [Any]!) {
        print("EMChatManagerDelegate2222222")
    }
    /// 会话列表发生变化
    /// - Parameter aConversationList: 会话列表
    func conversationListDidUpdate(_ aConversationList: [Any]!) {
        print("EMChatManagerDelegate3333333")

    }
}

extension Pet_TabbarViewController:AgoraRtmDelegate,AgoraRtmCallDelegate{
    
    func rtmKit(_ kit: AgoraRtmKit, connectionStateChanged state: AgoraRtmConnectionState, reason: AgoraRtmConnectionChangeReason) {
        if state.rawValue == 5 {
        }
        print(state.rawValue)
        print("connectionStateChanged==--------  ")
    }
    func rtmCallKit(_ callKit: AgoraRtmCallKit, remoteInvitationReceived remoteInvitation: AgoraRtmRemoteInvitation) {
        
        print("remoteInvitationReceived===---------   ")
        let isVideo = self.requestCaptureAuthorizationByMediaType(mediaType: "")
        if isVideo == false {
            let alert = UIAlertController(title: "Camera Permission Apply", message: "To start video chatting，allow app to access your canmera and microphone in app stting。", preferredStyle: .alert)
            let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
            let okaction = UIAlertAction(title: "OK", style: .default, handler: { (action) in
                let url = URL.init(string: UIApplication.openSettingsURLString)
                if UIApplication.shared.canOpenURL(url!){
                    UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                }
                
            })
            alert.addAction(cancel)
            alert.addAction(okaction)
            self.present(alert, animated: true, completion: nil)
            return
        }
        
        let isMic = self.requestCaptureAuthorizationByMicf()
        if isMic == false {
            let alert = UIAlertController(title: "Microphone Permission Apply", message: "Allow microphone access to use this feature", preferredStyle: .alert)
            let cancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
            let okaction = UIAlertAction(title: "OK", style: .default, handler: { (action) in
                // 麦克风
                AVAudioSession.sharedInstance().requestRecordPermission { (bool) in
                    if bool
                    {
                    }else
                    {
                        if self.requestCaptureAuthorizationByMicf() == false {
                            let url = URL.init(string: UIApplication.openSettingsURLString)
                            if UIApplication.shared.canOpenURL(url!){
                                UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                            }
                        }else
                        {
                        }

                    }
                }
            })
            alert.addAction(cancel)
            alert.addAction(okaction)
            self.present(alert, animated: true, completion: nil)
            return
        }
        let vc = TEA_VideoViewController()
        vc.remoteInvitation = remoteInvitation
        vc.isRecept = true
        vc.hidesBottomBarWhenPushed = true
        let navCtrl = self.selectedViewController as? NavigationInterface
        navCtrl?.pushViewController(vc, animated: false)
    }

}


class MyTabBar: UITabBar {
    
    let backV = UIView.init(frame: .init(x: 15.Fit, y: -12.Fit, width: screenWidth - 30.Fit, height:64.Fit))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        itemPositioning = .centered
        backgroundImage = UIImage()
        backgroundColor = .clear
        shadowImage = UIImage()
        itemSpacing = 10.Fit
        
        backV.backgroundColor = .black
        backV.setAllCorners(corner: 64.Fit/2)
        self.addSubview(backV)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder)")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        //当前tabbai的宽度和高度
    }
    
}
